package com.servlet;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JsonUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@WebServlet("/FileUploadServlet")

public class FileUploadServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //创建对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);

        JsonUtil jsonUtil = new JsonUtil();
        //解析req对象
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);

            for (FileItem fileItem : fileItems) {
                if (fileItem.isFormField()){ //判断传递过来的是不是普通的表单字段，否则是文件字段
                    System.out.println("普通表单字段的名称为:"+fileItem.getFieldName() +"对应的值为:"+fileItem.getString());
                }else{
                    //这里接受文件上传字段，用io流读取
                    //应该把文件保存到项目运行的tomcat对应的目录下
                    String realPath = request.getServletContext().getRealPath("/img");
                    System.out.println(realPath);
                    File file = new File(realPath);

                    if (!file.exists()){
                        file.mkdirs();
                    }
                    String uploadFileName = fileItem.getName();
                    System.out.println("上传的文件名"+uploadFileName);

                    FileOutputStream fileOutputStream = new FileOutputStream(new File(file, uploadFileName));
                    InputStream inputStream =  fileItem.getInputStream();
                    byte[] buf = new byte[1024];
                    int len =0;
                    while( (len = inputStream.read(buf))!=-1){
                        /// System.out.println("收到的文件内容为:"+new String(buf,0,len));
                        fileOutputStream.write(buf,0,len);
                    }
                    inputStream.close();
                    fileOutputStream.close();
                    System.out.println("文件上传成功");

                    jsonUtil.setCode(0);
                    jsonUtil.setMsg("成功");
                    //http://IP:8089/MyWeb2/img/文件名

                    Integer port =  request.getLocalPort();//得到端口号
                    String ip  =   request.getLocalAddr();;//得到ip
                    String contextPath1 =   request.getContextPath();//得到上下文路径

                    String imgPath = "http://"+ip+":"+port+contextPath1+"/img/"+uploadFileName;

                    jsonUtil.setData(imgPath);
                }
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
            jsonUtil.setCode(1);
            jsonUtil.setMsg("文件上传失败:"+e.getMessage());
        }

        response.setContentType("text/html;charset=utf-8");
        PrintWriter printWriter = response.getWriter();

        GsonBuilder gsonBuilder = new GsonBuilder();
        Gson gson = gsonBuilder.create();


        printWriter.print(gson.toJson(jsonUtil));

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

}
 
 
 

